package com.sjy.project.fym.signin.service.impl;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sjy.common.entity.SecuryUserDetail;
import com.sjy.common.exception.BusinessException;
import com.sjy.common.exception.ServiceException;
import com.sjy.common.utils.DateUtils;
import com.sjy.common.utils.LocationUtils;
import com.sjy.common.utils.StringUtils;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sjy.project.fym.signin.mapper.FyUserSigninMapper;
import com.sjy.project.fym.place.domain.FyPlace;
import com.sjy.project.fym.place.mapper.FyPlaceMapper;
import com.sjy.project.fym.signin.domain.FyUserSignin;
import com.sjy.project.fym.signin.domain.FyUserSigninVo;
import com.sjy.project.fym.signin.service.IFyUserSigninService;
import com.sjy.project.fym.user.domain.FyUser;
import com.sjy.project.fym.user.mapper.FyUserMapper;
import com.sjy.common.utils.text.Convert;

/**
 * 人员签到打卡记录Service业务层处理
 * 
 * @author sjy
 * @date 2022-04-18
 */
@Service
public class FyUserSigninServiceImpl implements IFyUserSigninService 
{
    @Autowired
    private FyUserSigninMapper fyUserSigninMapper;
    @Autowired
    private FyPlaceMapper fyPlaceMapper;
    @Autowired
    private FyUserMapper fyUserMapper;

    /**
     * 查询人员签到打卡记录
     * 
     * @param id 人员签到打卡记录主键
     * @return 人员签到打卡记录
     */
    @Override
    public FyUserSignin selectFyUserSigninById(Long id)
    {
        return fyUserSigninMapper.selectFyUserSigninById(id);
    }

    /**
     * 查询人员签到打卡记录列表
     * 
     * @param fyUserSignin 人员签到打卡记录
     * @return 人员签到打卡记录
     */
    @Override
    public List<FyUserSignin> selectFyUserSigninList(FyUserSignin fyUserSignin)
    {
        return fyUserSigninMapper.selectFyUserSigninList(fyUserSignin);
    }

    /**
     * 新增人员签到打卡记录
     * 
     * @param fyUserSignin 人员签到打卡记录
     * @return 结果
     */
    @Override
    public int insertFyUserSignin(FyUserSignin fyUserSignin)
    {
        fyUserSignin.setCreateTime(DateUtils.getNowDate());
        return fyUserSigninMapper.insertFyUserSignin(fyUserSignin);
    }

    /**
     * 修改人员签到打卡记录
     * 
     * @param fyUserSignin 人员签到打卡记录
     * @return 结果
     */
    @Override
    public int updateFyUserSignin(FyUserSignin fyUserSignin)
    {
        fyUserSignin.setUpdateTime(DateUtils.getNowDate());
        return fyUserSigninMapper.updateFyUserSignin(fyUserSignin);
    }

    /**
     * 批量删除人员签到打卡记录
     * 
     * @param ids 需要删除的人员签到打卡记录主键
     * @return 结果
     */
    @Override
    public int deleteFyUserSigninByIds(String ids)
    {
        return fyUserSigninMapper.deleteFyUserSigninByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除人员签到打卡记录信息
     * 
     * @param id 人员签到打卡记录主键
     * @return 结果
     */
    @Override
    public int deleteFyUserSigninById(Long id)
    {
        return fyUserSigninMapper.deleteFyUserSigninById(id);
    }
    
    /**
     * 用户根据核酸点ID进行签到，区分上午下午；一个时间段同一个人只能签到一次
     * @param placeId
     * @param user
     * @return
     */
    public boolean signinByPlace(Long placeId,BigDecimal lng,BigDecimal lat,SecuryUserDetail user) throws Exception{
    	
    	//检测placeId是否有效
    	FyPlace place = fyPlaceMapper.selectFyPlaceByPlaceId(placeId);
    	if(StringUtils.isNull(place)||!"1".equals(place.getStatus())) {
    		 throw new BusinessException("当前核酸检测点已失效或未启用！");
    	}
    	//检测当前用户所在队伍是否绑定的当前placeId
    	FyUser fyUser = fyUserMapper.selectFyUserByUserId(user.getUserId());
    	if(StringUtils.isNull(fyUser.getFyTeam())) {
    		throw new BusinessException("请联系管理员-用户未绑定队伍！");
    	}
//    	if(fyUser.getFyTeam().getPlaceId()==null||!placeId.equals(fyUser.getFyTeam().getPlaceId())) {
//    		throw new BusinessException("请联系管理员-您所在的队伍无法在当前核酸点打卡！");
//    	}

    	//获取当前时间点  11点之前算早上 = 1，11点之后算下午 = 2
    	Calendar calendar = Calendar.getInstance();
    	int hour = calendar.get(Calendar.HOUR_OF_DAY);
    	
    	//判断能当前经纬度跟打卡点经纬度距离
    	double dis = LocationUtils.getDistance(lat.doubleValue(), lng.doubleValue(), place.getLat().doubleValue(), place.getLng().doubleValue());
    	if(place.getSignInRadius()!=null&&dis>place.getSignInRadius()) {
    		String remark = "当前距离打卡点"+dis+"米，请到核酸检测点:"+place.getPlaceName()+"("+place.getAddr()+")"+place.getSignInRadius()+"米范围内进行打卡!";
    		insertSignin(fyUser,place,lng,lat,remark,hour);
    		throw new BusinessException(remark);
    	}
    	//查询当前用户当前时间段打卡记录
    	
    	FyUserSignin sign = new FyUserSignin();
    	sign.setUserId(fyUser.getUserId());
    	//sign.setPlaceId(place.getPlaceId());
    	sign.setSigninType(hour>=11?"2":"1");
    	sign.setSigninStatus("0");
    	Map<String,Object> params  = new HashMap<String,Object>();
    	params.put("currDayFlag", "1");
    	sign.setParams(params);
    	
    	List<FyUserSignin> signins = fyUserSigninMapper.selectFyUserSigninList(sign);
    	if(signins.size()>0) {
    		FyUserSignin existSignin = signins.get(0);
    		if(!existSignin.getPlaceId().equals(placeId)) {
    			String remark = "无法打卡，因为已经在"+existSignin.getPlaceName()+"签到过";
    			insertSignin(fyUser,place,lng,lat,remark,hour);
        		throw new BusinessException(remark);
    		}
    		String remark = "重复签到!";
    		//insertSignin(fyUser,place,lng,lat,remark,hour);
    		throw new BusinessException(remark);
    	}else {
    		insertSignin(fyUser,place,lng,lat,"",hour);
    	}
    	
    	return true;
    }
    
    private boolean insertSignin(FyUser fyUser,FyPlace place,BigDecimal lng,BigDecimal lat,String remark,int hour) {
    	//判断能签到 正常插入后台表，重复签到-插入异常数据到后台表
    	FyUserSignin s = new FyUserSignin();
    	s.setCreateBy(fyUser.getUserId()+"");
    	s.setCreateTime(new Date());
    	s.setPlaceId(place.getPlaceId());
    	s.setPlaceName(place.getPlaceName());
    	s.setSigninLat(lat);
    	s.setSigninLng(lng);
    	s.setSigninType(hour>=11?"2":"1"); //fym_signin_type 1上午 2下午  这个地方以11点钟为界限  11点之前算上午，其他时间算下午
    	s.setTeamId(fyUser.getFyTeam().getTeamId());
    	s.setTeamName(fyUser.getFyTeam().getTeamName());
    	s.setUserId(fyUser.getUserId());
    	s.setUserName(fyUser.getUserName());
    	s.setSigninStatus(StringUtils.isBlank(remark)?"0":"1");//sys_common_status 0 成功  1失败
    	s.setRemark(remark);
    	
    	return fyUserSigninMapper.insertFyUserSignin(s)>0;
    }
    
    /**
     * 根据场所ID或者队伍ID获取签到相关统计信息
     * @param placeId
     * @param teamId
     * @return
     */
    public Map<String,Object> getSigninStaByPlaceOrTeamId(Long placeId,Long teamId){
    	return fyUserSigninMapper.getSigninStaByPlaceOrTeamId(placeId, teamId);
    }
    /**
     * 根据场所ID或者队伍ID获取当前打卡人员清单
     * @param placeId
     * @param teamId
     * @return
     */
    public List<FyUserSigninVo> getSigninListByPlaceOrTeamId(Long placeId,Long teamId){
    	return fyUserSigninMapper.getSigninListByPlaceOrTeamId(placeId, teamId);
    }
    
    public static void  main(String[] args) {
    	Calendar calendar = Calendar.getInstance();
    	int hour = calendar.get(Calendar.HOUR_OF_DAY);
    	System.out.println(hour);
    }
    
}
